# -*- coding: utf-8 -*-
import logging

from pylons import (request,
                    response,
                    session,
                    tmpl_context as c,
                    url,
                    app_globals as g)
from pymongo.objectid import ObjectId
from mimetypes import guess_type
from pylons.controllers.util import abort, redirect
from craneserver.lib.base import BaseController, render
from repoze.what.plugins.pylonshq import ControllerProtector, ActionProtector
from repoze.what.predicates import in_group, is_user, has_permission, in_any_group
import uuid
import simplejson

log = logging.getLogger(__name__)

@ControllerProtector(in_any_group('Super User','HPC User', 'Web Hosting User', 'IaaS User'))
class StorageController(BaseController):

    def list(self):
        identity = request.environ.get('repoze.who.identity')
        userid = identity['repoze.who.userid']
        fs = g.gridfs(userid)
        result = [{'id': str(item['_id']),
                   'filename': item['filename'],
                   'length': item['length'],
                   'md5': item['md5'],
                   'uploadDate': str(item['uploadDate'])}
                    for item in fs._GridFS__files.find()]
        return simplejson.dumps(result)

    def upload(self):
        try:
            identity = request.environ.get('repoze.who.identity')
            userid = identity['repoze.who.userid']
            fs = g.gridfs(userid)
            the_file = None
            uploaded_file = None
            filename = None
            dir = None
            if request.is_xhr:
                the_file = request.environ['wsgi.input']
                filename = request.params.get('file')
                dir = request.params.get('dir')
                #print the_file, filename
            else:
                uploaded_file = request.params['file']
                the_file = uploaded_file.file
                filename = request.params.get('path')
                dir = request.params.get('dir')
                if not filename:
                    filename = uploaded_file.filename
            if dir:
                filename = dir + '/' + filename
            if fs.exists(filename=filename):
                abort(409)
            id = fs.put(the_file, filename=filename)
            #print id
            return simplejson.dumps({ 'id': str(id), 'filename': filename, 'success': True })
        except Exception as error:
            return simplejson.dumps({ 'id': None, 'error': str(error) })

    def upload_tmpfile(self):
        try:
            identity = request.environ.get('repoze.who.identity')
            userid = identity['repoze.who.userid']
            fs = g.gridfs(userid)
            the_file = None
            uploaded_file = None
            filename = None
            tempdir = str(uuid.uuid4())
            if request.is_xhr:
                the_file = request.environ['wsgi.input']
                filename = request.params.get('file')
                #print the_file, filename
            else:
                uploaded_file = request.params['file']
                the_file = uploaded_file.file
                filename = request.params.get('path')
                if not filename:
                    filename = uploaded_file.filename
            filename = r'/tmp/'+ tempdir + r'/' + filename
            if fs.exists(filename=filename):
                abort(409)
            id = fs.put(the_file, filename=filename)
            #print id
            return simplejson.dumps({ 'id': str(id), 'filename': filename, 'success': True })
        except Exception as error:
            return simplejson.dumps({ 'id': None, 'error': str(error) })

    def form(self):
        return render('upload.mako')

    def update(self):
        #POST
        try:
            identity = request.environ.get('repoze.who.identity')
            userid = identity['repoze.who.userid']
            fs = g.gridfs(userid)
            #filename = request.params.get('path')
            the_file = None
            uploaded_file = None
            filename = None
            dir = None
            if request.is_xhr:
                the_file = request.environ['wsgi.input']
                filename = request.params.get('file')
                dir = request.params.get('dir')
                #print the_file, filename
            else:
                uploaded_file = request.params['file']
                the_file = uploaded_file.file
                filename = request.params.get('path')
                dir = request.params.get('dir')
                if not filename:
                    filename = uploaded_file.filename
            if dir:
                filename = dir + '/' + filename
            if not fs.exists(filename=filename):
                abort(404)
            id = fs.put(the_file, filename=filename)
            #print id
            return simplejson.dumps({ 'id': str(id), 'filename': filename, 'success': True })
        except Exception as error:
            return simplejson.dumps({ 'id': None, 'error': str(error) })

    def deleteById(self, id):
        identity = request.environ.get('repoze.who.identity')
        userid = identity['repoze.who.userid']
        fs = g.gridfs(userid)
        try:
            fs.delete(ObjectId(id))
            return simplejson.dumps({ 'success': True })
        except:
            abort(404)

    def delete(self):
        identity = request.environ.get('repoze.who.identity')
        userid = identity['repoze.who.userid']
        fs = g.gridfs(userid)
        filename = request.params.get('path')
        if not filename:
            abort(404)
        else:
            try:
                id = fs.get_last_version(filename)._id
                fs.delete(id)
                return simplejson.dumps({ 'success': True })
            except:
                abort(404)



    def downloadById(self, id):
        identity = request.environ.get('repoze.who.identity')
        userid = identity['repoze.who.userid']
        fs = g.gridfs(userid)

        try:
            f = fs.get(ObjectId(id))
            filename = f.name.split(r'/')
            filename.reverse()
            filename = filename[0]
            response.headers['Content-Length'] = f.length
            response.headers['Pragma'] =  'public'
            response.headers['Cache-Control'] = 'max-age=0'
            response.content_type = guess_type(filename)[0] or 'text/plain'
            response.charset = 'utf8'
            response.headers['Content-Disposition'] = 'attachment; filename="%s"'% filename
            return f
        except:
            abort(404)

    def download(self):
        identity = request.environ.get('repoze.who.identity')
        userid = identity['repoze.who.userid']
        fs = g.gridfs(userid)
        filename = request.params.get('path')
        if not filename:
            abort(404)
        else:
            try:
                f = fs.get_last_version(filename)
                filename = f.name.split(r'/')
                filename.reverse()
                filename = filename[0]
                response.headers['Content-Length'] = f.length
                response.headers['Pragma'] =  'public'
                response.headers['Cache-Control'] = 'max-age=0'
                response.content_type = guess_type(filename)[0] or 'text/plain'
                response.charset = 'utf8'
                response.headers['Content-Disposition'] = 'attachment; filename="%s"'% filename
                return f
            except:
                abort(404)
